Skip to main content

Convert sorted array to binary search tree

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/

/**
* @param {TreeNode} root
* @return {boolean}
*/
var isValidBST = function(root) {
function validate(node, min, max) {
if (!node) return true;

if ((min !== null && node.val <= min) || (max !== null && node.val >= max)) {
return false;
}

return validate(node.left, min, node.val) && validate(node.right, node.val, max);
}

return validate(root, null, null);
};